package com.swdegao.iot;

import org.mybatis.spring.annotation.MapperScan;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.support.BeanDefinitionBuilder;
import org.springframework.beans.factory.support.DefaultListableBeanFactory;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration;
import org.springframework.boot.builder.SpringApplicationBuilder;
import org.springframework.boot.web.servlet.ServletComponentScan;
import org.springframework.boot.web.servlet.support.SpringBootServletInitializer;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;


@SpringBootApplication
//@EnableAutoConfiguration(exclude={DataSourceAutoConfiguration.class})
// 监听web生命周期
@ServletComponentScan(value = "com.swdegao.iot.netty.listener")
// 扫描mybatis mapper包
@MapperScan(value = "com.swdegao.iot.netty.mapper")
public class SwdegaoIotMgtServerApplication extends SpringBootServletInitializer implements ApplicationContextAware  {

	// 定义一个全局的记录器，通过LoggerFactory获取
	private final static Logger logger = LoggerFactory.getLogger(SwdegaoIotMgtServerApplication.class);
	private static ApplicationContext applicationContext;
	private static DefaultListableBeanFactory defaultListableBeanFactory;

	public static void main(String[] args) {
		SpringApplication.run(SwdegaoIotMgtServerApplication.class, args);
		logger.info("---------物联设备管理中心Netty服务器启动---------");
	}
	@Override
	protected SpringApplicationBuilder configure(SpringApplicationBuilder builder) {
        return builder.sources(this.getClass());
    }

	@SuppressWarnings("static-access")
	@Override
	public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
		this.applicationContext = applicationContext;
		defaultListableBeanFactory = (DefaultListableBeanFactory) applicationContext.getAutowireCapableBeanFactory();
	}

	@SuppressWarnings("unchecked")
	public static <T> T getBean(Class<T> clazz) {
		BeanDefinitionBuilder beanDefinitionBuilder = BeanDefinitionBuilder.genericBeanDefinition(clazz);
		String className = clazz.getName();
		defaultListableBeanFactory.registerBeanDefinition(className, beanDefinitionBuilder.getBeanDefinition());
		return (T) applicationContext.getBean(className);
	}

	public static void destroy(String className) {
		defaultListableBeanFactory.removeBeanDefinition(className);
		System.out.println("destroy " + className);
	}

}
